package com.itheima.server.interceptor;

import com.itheima.commons.utils.JwtUtils;
import com.itheima.model.domain.User;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class TokenInterCeptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info(request.getRequestURI());
        log.info(request.getMethod());
        //1.获取请求头
        String token = request.getHeader("Authorization");
        //2.使用工具类.判断token是否有效
        /*if(!JwtUtils.verifyToken(token)){
            response.setStatus(401);
            return false;
        }*/
        //有效先将用户信息放入到threadlocal中

        Claims claims = JwtUtils.getClaims(token);
        User user = new User();
        user.setId(Long.valueOf((Integer) claims.get("id")));
        user.setMobile((String) claims.get("mobile"));
        UserHolder.set(user);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }

}
